package concurrecy;

import java.util.Random;
import java.util.concurrent.TimeUnit;

class NeedCleanup {
    private String name;
    public NeedCleanup(String name) {
        this.name = name;
    }

    public void cleanup() {
        System.out.println("Cleanup " + name);
    }
}

/**
 * 中断一个线程的两种方式
 */
public class InterruptThreadDemo {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                while (!Thread.interrupted()) {
                    NeedCleanup n1 = new NeedCleanup("1");
                    try {
                        System.out.println("sleep 1 seconds");
                        TimeUnit.SECONDS.sleep(1);
                        System.out.println("end sleep");
                        NeedCleanup n2 = new NeedCleanup("2");
                        try {
                            double d = 1;
                            System.out.println("start math calc ");
                            long p = System.currentTimeMillis();
                            for (int i = 0; i < 500000000; i++) {
                                d *= ((Math.E + Math.PI) / i) * Math.PI;
                            }
                            System.out.println("end math calc " + (System.currentTimeMillis() - p));
                        } finally {
                            n2.cleanup();
                        }
                    } finally {
                        n1.cleanup();
                    }
                }
                System.out.println("exit from while");
            } catch (InterruptedException e) {
                System.out.println("exit from InterruptedException");
            }
        });

        thread.start();
        int time = new Random().nextInt(2000);
        TimeUnit.MILLISECONDS.sleep(time);
        System.out.println("thread.interrupt();");
        thread.interrupt();
    }
}
